package controllers

import (
	"encoding/json"
	"errors"

	md "gitee.com/countpoison/youbei/models"
	"gitee.com/countpoison/youbei/utils/mail"
)

// MailInput ...
type MailSendInput struct {
	User string `json:"user"`
}

//MailServerUpdate ...
func (c *MainController) MailServerUpdate() {
	ob := new(md.MailServer)
	c.APIReturn(500, "解析数据失败", json.Unmarshal(c.Ctx.Input.RequestBody, ob))
	c.APIReturn(500, "修改mail server失败", ob.Update())
	c.APIReturn(200, "修改成功", nil)
}

func (c *MainController) GetMail() {
	mailserver := new(md.MailServer)
	bol, err := md.Localdb().Get(mailserver)
	c.APIReturn(500, "获取失败", err)
	if !bol {
		c.APIReturn(500, "未配置", errors.New("未配置"))
	}
	c.APIReturn(200, "获取成功", mailserver)
}

//MailSendAdd ...
func MailSendAdd(sub, body string) error {
	sendmail := new(md.MailSend)
	mailcon, err := mail.MailInit()
	if err != nil {
		return err
	}
	sendmail.FromUser = mailcon.FromPasswd
	sendmail.FromPasswd = mailcon.FromPasswd
	sendmail.Host = mailcon.Host
	sendmail.Port = mailcon.Port
	sendmail.ToUsers = mailcon.ToUsers
	sendmail.Body = body
	sendmail.Subject = sub
	if err := mailcon.SendMail(sub, body); err != nil {
		return err
	}
	return sendmail.Add()
}

type MailText struct {
	Sub  string `json:"sub"`
	Text string `json:"text"`
}

func (c *MainController) MailTest() {
	mailtext := new(MailText)
	c.APIReturn(500, "解析失败", json.Unmarshal(c.Ctx.Input.RequestBody, mailtext))
	c.APIReturn(500, "失败", MailSendAdd(mailtext.Sub, mailtext.Text))
	c.APIReturn(200, "成功", nil)
}
